package com.example.whatrubbish.controller;

import com.example.whatrubbish.model.Commodity;
import com.example.whatrubbish.service.CommodityService;
import com.example.whatrubbish.utils.Constants;
import com.example.whatrubbish.utils.DemoException;
import com.example.whatrubbish.utils.JsonResult;
import com.example.whatrubbish.vo.CommodityDetailVO;
import com.example.whatrubbish.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/commodity")
public class CommodityController {
    @Autowired
    CommodityService commodityService;

    @GetMapping("")
    public JsonResult get(@RequestParam("title") String title,
                          @RequestParam("status") Integer status,
                          @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        PageBean<CommodityDetailVO> pageBean = commodityService.findCommodityWithPage(title, status, pageIndex, pageSize);
        return new JsonResult(Constants.STATUS_SUCCESS, "success", pageBean);
    }

    @GetMapping("/getOne")
    public JsonResult getOne(@RequestParam Long id) {
        CommodityDetailVO commodityDetailVO = commodityService.selectByPrimaryKey(id);
        return new JsonResult(Constants.STATUS_SUCCESS, "success", commodityDetailVO);
    }

    @PostMapping("")
    public JsonResult insert(@RequestBody @Validated CommodityDetailVO commodityDetailVO) {
        commodityService.insert(commodityDetailVO);
        return new JsonResult(Constants.STATUS_SUCCESS, "success");
    }

    @PutMapping("")
    public JsonResult update(@RequestBody CommodityDetailVO commodityDetailVO){
        commodityService.update(commodityDetailVO);
        return new JsonResult(Constants.STATUS_SUCCESS, "success");
    }

    @DeleteMapping("")
    public JsonResult delete(@RequestParam("id") Long id) {
        try {
            commodityService.delete(id);
        } catch (Exception e) {
            return new JsonResult(Constants.STATUS_FAIL, e.getMessage());
        }

        return new JsonResult(Constants.STATUS_SUCCESS, "success");
    }
}
